<?php


class CollectionRelationTable extends Doctrine_Table {

    public static function getInstance() {
        return Doctrine_Core::getTable('CollectionRelation');
    }

    public function addFindByCollectionAndIdentifierQuery($collectionUin,array $typeIdentifiers, $inverseRelation = false, $sortByName = false, Doctrine_Query $q = null) {
        if ($q == null) {
            $q  = $this->createQuery();
        }
        $q->innerJoin('CollectionRelation.RelationType rt');

        if ($sortByName) {
            $q->innerJoin('CollectionRelation.relatedItem ri');
            $q->orderBy('ri.CollectionName');
        }



        $q->andWhereIn('rt.typeValue', $typeIdentifiers);
        if ($inverseRelation) {
            $q->addWhere('relatedItemUin = ?',$collectionUin);
        } else {
            $q->addWhere('thisCollectionUin = ?',$collectionUin);
        }

        return $q;
    }

    public function getCollectionRelationsQuery(CollectionItem $collectionItem) {
        $q = $this->createQuery();
        $q->innerJoin('CollectionRelation.RelationType rt ');
        $q->innerJoin('CollectionRelation.relatedItem ri');
        $q->where('thisCollectionuin = ? ',$collectionItem->getUin());
        $q->orderby('rt.displayGroupBy, rt.typeName, rt.typeValue, ri.collectionName');
        return $q;
    }

    public function getRelatingCollectionsQuery(CollectionItem $collectionItem) {
        $q = $this->createQuery();
        $q->innerJoin('CollectionRelation.RelationType rt ');
        $q->innerJoin('CollectionRelation.thisItem ti');
        $q->where('relatedItemUin = ? ',$collectionItem->getUin());
        $q->orderby('rt.displayGroupBy, rt.typeName, rt.typeValue, ti.collectionName');
        return $q;
    }
}